package com.padakeji.android.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.ColorInt;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.padakeji.android.ui.R;

/**
 * Created by atanl on 2016/3/2.
 */
public class RoundFrameLayout extends FrameLayout {

    private float mCornerRadius;
    private float mBorderWith;
    private int mBorderColor = Color.parseColor("#00000000");

    public RoundFrameLayout(Context context) {
        this(context, null);
    }

    public RoundFrameLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundFrameLayout, defStyleAttr, R.style.RoundFrameLayoutDefaultStyle);

        mCornerRadius = a.getDimension(R.styleable.RoundFrameLayout_rfl_cornerRadius, 0);
        mBorderWith = a.getDimension(R.styleable.RoundFrameLayout_rfl_borderWidth, 0);
        mBorderColor = a.getColor(R.styleable.RoundFrameLayout_rfl_borderColor, Color.parseColor("#00000000"));

        init();
    }

    private void init() {
    }

    public void setBorderColor(String colorString) {
        mBorderColor = Color.parseColor(colorString);
        invalidate();
    }

    public void setBorderColor(@ColorInt int colorInt) {
        mBorderColor = colorInt;
        invalidate();
    }

    public void setBorderWith(float borderWith) {
        mBorderWith = borderWith;
        invalidate();
    }

    public void setmBornerRadius(float radius) {
        mCornerRadius = radius;
        invalidate();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int count = canvas.save();

        Path borderPath = new Path();
        borderPath.addRoundRect(new RectF(mBorderWith, mBorderWith, getWidth() - mBorderWith, getHeight() - mBorderWith), mCornerRadius - mBorderWith, mCornerRadius - mBorderWith, Path.Direction.CCW);
        canvas.clipPath(borderPath);

        super.dispatchDraw(canvas);

        canvas.restoreToCount(count);

        Paint borderPaint = new Paint();
        borderPaint.setAntiAlias(true);
        borderPaint.setColor(mBorderColor);
        borderPaint.setStrokeWidth(mBorderWith);
        borderPaint.setStyle(Paint.Style.STROKE);
        canvas.drawRoundRect(new RectF(mBorderWith/2, mBorderWith/2, getWidth() - mBorderWith/2, getHeight() - mBorderWith/2), mCornerRadius, mCornerRadius, borderPaint);

    }
}
